﻿using System;
using System.IO;
using System.Text;

namespace Best.SmartCms.Utility
{
    public static class PlainFileHelper
    {
        /// <summary>
        /// 获得文本文件的内容
        /// </summary>
        /// <param name="filePath">文件完整路径，包括文件名</param>
        /// <returns>文本文件的内容</returns>
        public static string GetFileContent(string filePath)
        {
            StringBuilder content = new StringBuilder();
            StreamReader reader = null;
            try
            {
                reader = new StreamReader(filePath);
                for (string line = reader.ReadLine(); line != null; line = reader.ReadLine())
                    content.Append(line);
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
            }
            return content.ToString();
        }

        /// <summary>
        /// 写文本文件
        /// </summary>
        /// <param name="filePath">文件完整路径，包括文件名</param>
        /// <param name="isAppend">是否以Append的形式写文件</param>
        /// <param name="content">文件内容</param>
        /// <param name="fileEncoding">文件编码</param>
        /// <returns>写文件是否成功</returns>
        public static bool WriteFile(string filePath, bool isAppend, string content, Encoding fileEncoding)
        {
            StreamWriter sw = null;
            try
            {
                sw = new StreamWriter(filePath, isAppend, fileEncoding);
                sw.WriteLine(content);
                sw.Close();
                return true;
            }
            catch (Exception)
            {
                if (sw != null)
                {
                    sw.Close();
                }
                return false;
            }
        }
    }
}